package com.caigou.controller;

import com.caigou.bean.empire.entity.EmpireSyncArticleData;
import com.caigou.component.EmpireDataSyncComponent;
import com.caigou.component.RedisComponent;
import com.caigou.enums.ResponseEnum;
import com.caigou.mapper.cms.ArticleSyncDataMapper;
import com.caigou.service.EmpireDataSyncService;
import com.caigou.util.Result;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
public class EmpireDataSyncController {

    @Resource
    private EmpireDataSyncService empireDataSyncService;
    @Resource
    private ArticleSyncDataMapper articleSyncDataMapper;
    @Resource
    private RedisComponent redisComponent;
    @Resource
    private EmpireDataSyncComponent empireDataSyncComponent;

    // 关闭定时任务
    @RequestMapping("/closeEmpireDataSync")
    public Result closeEmpireDataSync(String empireDataSyncStatus, String empireNewDataSyncStatus){
        redisComponent.set("empireDataSyncStatus",empireDataSyncStatus);
        redisComponent.set("empireNewDataSyncStatus",empireNewDataSyncStatus);
        return Result.success(ResponseEnum.SUCCESS);
    }
    // 重置定时任务起始值
    @RequestMapping("/resetEmpireDataSyncId")
    public Result resetEmpireDataSyncId(String empireDataSyncLastTime, String empireNewDataSyncLastTime){
        redisComponent.set("empireDataSyncLastTime", empireDataSyncLastTime);
        redisComponent.set("empireNewDataSyncLastTime", empireNewDataSyncLastTime);
        return Result.success(ResponseEnum.SUCCESS);
    }

    // 处理出错的任务
    @RequestMapping("/disposeErrorData")
    public Result disposeErrorData(){
        List<Integer> errList = articleSyncDataMapper.loadErrorData();
        errList.forEach(item -> {
            EmpireSyncArticleData info = empireDataSyncService.loadEmpireSyncArticleDataById(item);
            if (null != info){
                empireDataSyncComponent.disposeData(info,-1);
            }
            // 如果处理完成之后，删除错误ID
            articleSyncDataMapper.disposeErrorData(item);
        });
        return Result.success(ResponseEnum.SUCCESS);
    }

    // 定时任务跑完之后，处理丢失的RSS数据
    @RequestMapping("/saveRssData")
    public Result saveRssData(){
        empireDataSyncService.saveRssData();
        return Result.success(ResponseEnum.SUCCESS);
    }
}
